

import store from '@/store/index'
import {
	routerTree
} from './router.config.js'
import {
  getUserMenuTree
} from '@/assets/request/api.js';
import { Message } from 'element-ui';

async function initAsyncRouter() {

  let userUniqueDynamicMenus = await getUserUniqueDynamicMenus()

  // 一级菜单
  let tempRoutes = buildMenuRoutes(userUniqueDynamicMenus)
  tempRoutes.routerTree.forEach(el => {
    if(el.children) {
      el.children.forEach(children => {
        routerTree.children.push(children)
      })
    } 
  })

  console.log(routerTree)

  // 添加动态路由 -- 必须做。 如果不做会陷入死循环。。
  store.commit('app/setRoutesTree', routerTree || [])

  console.log("菜单",tempRoutes.routerTree)
  // 左侧菜单 + 个人中心 + 首页 集合
  store.commit('app/setMenuTree', tempRoutes.routerTree || [])

  console.log("权限码",tempRoutes.limitedCodes)
  // 权限码
  store.commit('app/setLimitedCodes', tempRoutes.limitedCodes || [])

}

function getUserUniqueDynamicMenus() {
  return new Promise((resolve, reject) => {
    getUserMenuTree().then(res => {
      resolve(res.data)
    }).catch(err => {
      Message.error(err.message)
      reject(err)
    })
  })
}

function buildMenuRoutes (menus) {
  const tempRoutes = {
    routerTree: [],
    limitedCodes: []
  }
  menus.forEach(ele => {
    const tempObj = {}
    if (ele.children) {
      let menuRoutes = buildMenuRoutes(ele.children)
      tempObj.children = menuRoutes['routerTree']
      menuRoutes.limitedCodes.forEach(code => {
        tempRoutes['limitedCodes'].push(code)
      })
    }
    if(ele.path) {
      tempObj.parentId = ele.parentId
      tempObj.path = ele.path
      tempObj.name = ele.name
      tempObj.meta = ele.meta
      if(ele.component) {
        tempObj.component = () => import(`@/views/${ele.component}`)
      }
      tempRoutes['routerTree'].push(tempObj)
    }
    if(ele.meta.permissionCode) {
      tempRoutes['limitedCodes'].push(ele.meta.permissionCode)
    }
  })
  return tempRoutes
}


export default initAsyncRouter